/*******************************************************************************
 * Copyright (c) 2010 Eugene Vorobkalo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Eugene Vorobkalo - initial API and implementation
 *     Andrey Fedorov
 ******************************************************************************/
package org.droidpres.activity;

import java.sql.Date;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.MenuInflater;
import android.widget.*;
import org.droidpres.R;
import org.droidpres.adapter.DocumentListAdapter;
import org.droidpres.db.DB;
import org.droidpres.db.QueryHelper;
import org.droidpres.utils.Const;
import org.droidpres.utils.MenuItemInfo;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class DocumentListActivity extends AbsListActivity {
	private static final int MENU_EDIT					= Menu.FIRST;
	private static final int MENU_DELETE				= Menu.FIRST + 1;
	private static final int MENU_RESEND				= Menu.FIRST + 2;
	private static final int MENU_STATUS_EDIT			= Menu.FIRST + 3;
	private static final int MENU_STATUS_PREPARE_SEND	= Menu.FIRST + 4;

    private static final int DLG_APPLY_FILTER = 0;

    private TextView tvFilterText;

	public DocumentListActivity() {
		super(R.layout.document_list, DB.TABLE_DOCUMENT,
                new String[] {""},
				"");
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        tvFilterText = (TextView) findViewById(R.id.tvDocListFilter);
        ApplyFilter(1);
    }

	@Override
	protected CursorAdapter createAdapter(Cursor cursor) {
		return new DocumentListAdapter(this,
				R.layout.listrow,
				cursor, 
                new String[] {"_id", "CREATED_TIME", "client_name", "mainsumm", "docstate"},
                new int[] {R.id.textN, R.id.textDateTime, R.id.textClient, R.id.textSumm, R.id.imageView});
	}

	@Override
	protected Cursor createCursor() {
        //if(client_id > 0 ){
        //    mQueryHelper.appendFilter("CL", QueryHelper.FILTER_AND, "client_id = %d", client_id);
        //}
        mQueryHelper.appendFilter("have_number", QueryHelper.FILTER_AND, "number <> %d", 0);
        //mQueryHelper.appendJoin(DB.TABLE_CLIENT,"client_id",QueryHelper.JOIN_INNER,new String[] {"name as client_name"} );

		return mQueryHelper.CreateDocListCursor(mDataBase);
	}

	@Override
	protected List<MenuItemInfo> createContextMenus(int position, long id) {
		List<MenuItemInfo> menus = new LinkedList<MenuItemInfo>();
		Cursor cursor = getCursor();
		cursor.moveToPosition(position);
		int doc_state = QueryHelper.fieldByNameInt(cursor, "docstate");
		if (doc_state != Const.DOCSTATE_SEND) {
			menus.add(new MenuItemInfo(MENU_EDIT, R.string.lb_edit));
			menus.add(new MenuItemInfo(MENU_DELETE, R.string.lb_delete));
			switch (doc_state) {
			case Const.DOCSTATE_PREPARE_SEND:
				menus.add(new MenuItemInfo(MENU_STATUS_EDIT, R.string.lb_doc_status_edit));
				break;
			case Const.DOCSTATE_EDIT:
				menus.add(new MenuItemInfo(MENU_STATUS_PREPARE_SEND, R.string.lb_doc_status_preparesend));
				break;
			}
		} else {
            menus.add(new MenuItemInfo(MENU_EDIT, R.string.lb_doc_view));

            menus.add(new MenuItemInfo(MENU_RESEND, R.string.lb_resend));
		}
		return menus;
	}

	@Override
	protected String getContextMenuTitle(int position, long id) {
		Cursor cursor = getCursor();
		cursor.moveToPosition(position);
		DecimalFormat cf = SetupRootActivity.getCurrencyFormat(this);
		return getString(R.string.lb_doc_n) + cursor.getString(0) + " (" +
			cf.format(QueryHelper.fieldByNameFloat(cursor, "mainsumm")) + ")";
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		super.onContextItemSelected(item);
		AdapterView.AdapterContextMenuInfo mi = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		switch (item.getItemId()) {
			case MENU_EDIT:
				editDoc(mi.position, mi.id);
				return true;
			case MENU_DELETE: 
				mDataBase.delete(DB.TABLE_DOCUMENT,
						QueryHelper.KEY_ID + "=" + mi.id, null);
				requeryCursor();
				return true;
			case MENU_RESEND:
				changeStatus(mi.id, Const.DOCSTATE_PREPARE_SEND);
                return true;
			case MENU_STATUS_PREPARE_SEND:
				changeStatus(mi.id, Const.DOCSTATE_PREPARE_SEND);
				return true;
			case MENU_STATUS_EDIT:
				changeStatus(mi.id, Const.DOCSTATE_EDIT);
				return true;
		}
		return false;
	}

    private void NewDoc(){
        Bundle Extras = new Bundle();
        Extras.putLong(Const.EXTRA_DOC_ID, 0);
        Intent DocIntent = new Intent(this, DocActivity.class);
        DocIntent.putExtras(Extras);
        startActivity(DocIntent);
    }

    public void butNewDoc_OnClick(View v){
        NewDoc();
    }

    public void butFilterArea_OnClick(View v){
        showDialog(DLG_APPLY_FILTER);
    }

    @Override
    protected Dialog onCreateDialog(int dialogID) {
        super.onCreateDialog(dialogID);

        switch (dialogID) {
            case DLG_APPLY_FILTER:
                final CharSequence[] filter_names = new CharSequence[]
                        {
                                getString(R.string.lb_filterall),
                                getString(R.string.lb_filtertoday),
                                getString(R.string.lb_filterweek)
                        };

                Dialog dlg = new AlertDialog.Builder(this).
                    setTitle(R.string.lb_filter_title).
                    setItems(filter_names, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int item) {
                            ApplyFilter(item);
                        }
                    }).create();

                return dlg;

            default:
                return null;
        }
    }


	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		editDoc(position, id);
	}

	private void changeStatus(long id, int status) {
		ContentValues cval = new ContentValues();
		cval.put("docstate", status);
		mDataBase.update(DB.TABLE_DOCUMENT, cval,	QueryHelper.KEY_ID + "=" + id, null);
		requeryCursor();
	}
	
	private void editDoc(int position, long id) {
		Cursor cursor = getCursor();
		cursor.moveToPosition(position);

        Bundle Extras = new Bundle();
        Extras.putLong(Const.EXTRA_DOC_ID, id);

        Intent intent = new Intent(this, DocActivity.class);
		intent.putExtras(Extras);

		startActivity(intent);
	}

    @Override
    public void onResume(){
        super.onResume();
        requeryCursor();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.doc_list_menu, menu);
        return true;
    }

    private void ApplyFilter(int FilterType){
        Calendar cl;
        Date sqlDate;

        switch (FilterType){
            case 0:
                mQueryHelper.removeFilter("docdate");
                mAdapter.changeCursor(createCursor());
                //requeryCursor();
                tvFilterText.setText(getString(R.string.lb_filterall));
                break;
            case 1:
                cl = Calendar.getInstance();
                //cl.add(Calendar.DAY_OF_MONTH, 0);
                sqlDate = new Date(cl.getTime().getTime());
                mQueryHelper.appendFilter("docdate", QueryHelper.FILTER_AND, "CREATED_TIME > '"+sqlDate.toString()+"'");
                mAdapter.changeCursor(createCursor());
                //requeryCursor();
                tvFilterText.setText(getString(R.string.lb_filtertoday));
                break;
            case 2:
                cl = Calendar.getInstance();
                cl.add(Calendar.DAY_OF_MONTH, -7);
                sqlDate = new Date(cl.getTime().getTime());
                mQueryHelper.appendFilter("docdate", QueryHelper.FILTER_AND, "CREATED_TIME > '"+sqlDate.toString()+"'");
                mAdapter.changeCursor(createCursor());
                //requeryCursor();
                tvFilterText.setText(getString(R.string.lb_filterweek));
            default:
                return;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case (R.id.newdoc):
                NewDoc();
                break;
            case (R.id.filterall):
                ApplyFilter(0);
                break;
            case (R.id.filtertoday):
                ApplyFilter(1);
                break;
            case (R.id.filterweek):
                ApplyFilter(2);
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }

}
